﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace DataLoad.iContact.WinClient
{
    public class ExTextBox : TextBox
    {
        public event EventHandler ShouldExit;

        private void Exit()
        {
            Hide();

            if ((Parent != null) && (Parent.Controls.Contains(this)))
            {
                Parent.Controls.Remove(this);
            }
        }

        protected override void OnTextChanged(EventArgs e)
        {
            // Change the size
            using (Graphics g = this.CreateGraphics())
            {
                SizeF size = g.MeasureString(Text, Font);

                int newWidth = (int)size.Width;
                if (Parent != null)
                {
                    newWidth = Math.Min((int)size.Width, Parent.ClientSize.Width);
                }
                newWidth = Math.Max(newWidth, 50);

                Width = newWidth;

                if (Multiline)
                {
                    int newHeight = 100;
                    newHeight = Math.Min((int)size.Height, Parent.ClientSize.Height - Top);

                    Height = newHeight;
                }
            }

            base.OnTextChanged(e);
        }

        protected override void OnLeave(EventArgs e)
        {
            Exit();

            if (ShouldExit != null)
            {
                ShouldExit(this, e);
            }

            base.OnLeave(e);
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Return) && (!e.Control))
            {
                Exit();
                e.SuppressKeyPress = true;

                if (ShouldExit != null)
                {
                    ShouldExit(this, e);
                }
            }

            base.OnKeyDown(e);
        }
    }
}
